-module(geometry).

-include_lib("eunit/include/eunit.hrl").

-export([distance/4]).

-define(EARTH_RADIUS, 6378.137).

-define(RAD_PER_DEGREE, math:pi() / 180.0).

rad(D) ->
    D * ?RAD_PER_DEGREE.

distance(Latitude1, Longitude1, Latitude2, Longitude2) ->
    RadLat1 = rad(Latitude1),
    RadLat2 = rad(Latitude2),
    Dy = RadLat1 - RadLat2,
    Dx = rad(Longitude1) - rad(Longitude2),
    S = 2 * math:asin(math:sqrt(math:pow(math:sin(Dy/2),2) +
        math:cos(RadLat1) * math:cos(RadLat2) * math:pow(math:sin(Dx/2),2))),
    erlang:round(S * ?EARTH_RADIUS * 10000) / 10000.

distance_test() ->
    ?assertEqual(111.3195, distance(0,114.0,0,115.0)),
    ?assertEqual(109.6283, distance(10,114.0,10,115.0)),
    ?assertEqual(104.6059, distance(20,114.0, 20,115.0)),
    ?assertEqual(96.4052, distance(30,114.0, 30,115.0)),
    ?assertEqual(85.2752, distance(40,114.0, 40,115.0)),
    ?assertEqual(71.5543, distance(50,114.0, 50,115.0)),
    ?assertEqual(55.6592, distance(60,114.0, 60,115.0)),
    ?assertEqual(38.0731, distance(70,114.0, 70,115.0)).
